// permission.js
import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login", "/auth-redirect"];

router.beforeEach(async (to, from, next) => {
  
  console.log("to", to, from, next);
  NProgress.start();
  document.title = getPageTitle(to.meta.title);

  const hasToken = getToken();

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      console.log("登录状态,跳转其他页面");
      try {
        
        // 检查 Vuex 中是否有角色信息
        let hasRoles = store.getters.roles && store.getters.roles.length > 0;

        // if (!hasRoles) {
        //   console.log("没有角色信息，登录了");
        //   // 尝试从本地存储恢复用户信息
        //   const userInfo = store.state.user.userInfo;
        //   if (userInfo && userInfo.roles && userInfo.roles.length > 0) {
        //     // 更新 Vuex 状态
        //     store.commit("user/SET_ROLES", userInfo.roles);
        //     store.commit("user/SET_NAME", userInfo.loginName || "");
        //     store.commit("user/SET_AVATAR", userInfo.avatar || "");
        //     store.commit("user/SET_USERNAME", userInfo.userName || "");
        //     store.commit("user/SET_USERINFO", userInfo || {});
        //     hasRoles = true;
        //   }
        // }

        // if (hasRoles) {
          console.log("有角色信息,登录了");
          // 检查是否已经生成过权限路由
          const hasGeneratedRoutes =
            store.state.permission.addRoutes &&
            store.state.permission.addRoutes.length > 0;
          console.log(
            "是否已经生成过权限路由",
            store.state.permission.routes,
            store.state.permission.addRoutes
          );
          if (hasGeneratedRoutes) {
            console.log(
              "已生成权限路由...hasGeneratedRoutes",
              hasGeneratedRoutes
            );

            next();
          } else {
            console.log("生成权限路由...", store.getters.permission_routes);
            // 根据角色生成可访问的路由映射
            const accessRoutes = await store.dispatch(
              "permission/generateRoutes",
              store.getters.roles
            );
            router.addRoutes(accessRoutes);
            next({ ...to, replace: true }); 
          }
        // } else {
        //   // 没有有效的用户信息，需要重新登录
        //   Message.error("登录信息已过期，请重新登录");
        //   await store.dispatch("user/resetToken");
        //   next(`/login?redirect=${to.path}`);
        //   NProgress.done();
        // }
      } catch (error) {
        console.error("权限检查出错:", error);
        await store.dispatch("user/resetToken");
        Message.error(error.message || "权限检查出错");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    console.log("未登录...");
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (to.path === "/suittc") {
        sessionStorage.setItem("loginType", "suittc");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      } else {
        // 其他页面跳转到登录页
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
